package com.cindata

import com.cindata.dictionary.*
import grails.converters.JSON
import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Transactional
@Secured(['isAuthenticated()'])
class AccountController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def accountService
    def dataSource
    def springSecurityService

    // 机构列表页面
    def index()
    {
    }

    /** ------------------------------贷款机构 -----------------------------------**/
    def mortgageAccountIndex()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        //城市
        def city = params["city"]
        //行政区
        def district = params["district"]
        //注册资金
        def registeredCapitalStart = params["registeredCapitalStart"]
        //注册资金
        def registeredCapitalEnd = params["registeredCapitalEnd"]
        //信用评级
        def creditLevel = params["creditLevel"]
        //企业名称
        def name = params["name"]
        //经营状态
        def operatingState = params["operatingState"]
        //单位性质
        def unitNature = params["unitNature"]
        def estateQueryParam = new HashMap()
        def sort = params["sort"]
        def order = params["order"]

        def user = User.findById(springSecurityService.principal.id)
        def estateSql = " from Account e where e.type.code = 'MortgageAccount' and e.bankAccount.id in " + Account.FilterAccountSql(user)
        def sql = " "
        if (name && name != "")
        {
            sql += " and e.name like :name"
            estateQueryParam['name'] = '%' + name + '%'
        }
        if (city && city != "-1")
        {
            sql += " and e.city.zoneNumber = :city "
            estateQueryParam['city'] = city
        }
        if (district && district != "-1")
        {
            sql += " and e.district.zoneNumber = :district "
            estateQueryParam['district'] = district
        }
        if (registeredCapitalStart && registeredCapitalStart != "")
        {
            sql += "and e.registeredCapital >= :registeredCapitalStart "
            estateQueryParam['registeredCapitalStart'] = new BigDecimal(registeredCapitalStart) * 10000
        }
        if (registeredCapitalEnd && registeredCapitalEnd != "")
        {
            sql += "and e.registeredCapital <= :registeredCapitalEnd "
            estateQueryParam['registeredCapitalEnd'] = new BigDecimal(registeredCapitalEnd) * 10000
        }
        if (creditLevel && creditLevel != "")
        {
            sql += " and e.creditLevel like :creditLevel "
            estateQueryParam['creditLevel'] = "%" + creditLevel + "%"
        }
        if (operatingState && operatingState != "")
        {
            sql += " and e.operatingState = :operatingState "
            estateQueryParam['operatingState'] = operatingState
        }
        if (unitNature && unitNature != "")
        {
            sql += " and e.unitNature.id = :unitNature "
            estateQueryParam['unitNature'] = Long.parseLong(unitNature)
        }

        def countSql = " select count(e.id) from Account e where e.type.code = 'MortgageAccount' and e.bankAccount.id in " + Account.FilterAccountSql(user)
        countSql += sql

        if (order && sort)
        {
            sql += " order by e.${sort} ${order}"
        }
        else
        {
            sql += " order by e.modifiedDate desc "
        }
        estateSql += sql

        def accountList = Account.executeQuery(estateSql, estateQueryParam, [max: max, offset: offset])
        def accountCount = Account.executeQuery(countSql, estateQueryParam)
        respond accountList, model: [accountCount: accountCount[0], params: params], view: 'mortgageAccountIndex'
    }

    def mortgageAccountCreate()
    {
        respond new Account(params)
    }

    @Transactional
    def save(Account account)
    {
        if (account == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (account.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond account.errors, view: 'mortgageAccountCreate'
            return
        }

        account.save flush: true

        def mortgageList = params["mortgageList"]
        if (mortgageList instanceof String)
        {
            mortgageList = mortgageList?.split(",")
        }
        println mortgageList
        mortgageList?.each {
            def mortgage = Mortgage.findById(it)
            mortgage.mortgageAccount = account
            mortgage.mortgageCategory = MortgageCategory.findByCode('2')
            if (mortgage.validate())
            {
                mortgage.save flush: true
            }
            else
            {
                println mortgage.errors
            }
        }

        redirect action: 'mortgageAccountShow', id: account?.id
    }

    def mortgageAccountEdit(Account account)
    {
        respond account
    }

    @Transactional
    def update(Account account)
    {
        if (account == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (account.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond account.errors, view: 'mortgageAccountEdit'
            return
        }

        account.save flush: true

        def reMortgageList = Mortgage.findAllByMortgageAccountAndMortgageCategory(account, MortgageCategory.findByCode('2'))
        reMortgageList?.each {
            it.mortgageAccount = null
            it.save flush: true
        }

        def mortgageList = params["mortgageList"]
        if (mortgageList instanceof String)
        {
            mortgageList = mortgageList?.split(",")
        }
        mortgageList?.each {
            def mortgage = Mortgage.findById(it)
            mortgage.mortgageAccount = account
            mortgage.mortgageCategory = MortgageCategory.findByCode('2')
            if (mortgage.validate())
            {
                mortgage.save flush: true
            }
            else
            {
                println mortgage.errors
            }
        }


        redirect action: 'mortgageAccountShow', id: account?.id

    }

    def mortgageAccountShow(Account account)
    {
        respond account
    }

    // def bankAccountIndex()
    // {
    //     def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
    //     def offset = params.offset ? params.offset.toInteger() : 0
    //     //城市
    //     def city = params["city"]
    //     //行政区
    //     def district = params["district"]
    //     def name = params["name"]
    //     def address = params["address"]
    //     def estateQueryParam = new HashMap()
    //     def sort = params["sort"]
    //     def order = params["order"]

    //     def user = User.findById(springSecurityService.principal.id)
    //     def estateSql = " from Account e where e.type.code = 'BankAccount' and e.id in " + Account.FilterAccountSql(user)
    //     def sql = " "
    //     if (name && name != "")
    //     {
    //         sql += " and e.name like :name"
    //         estateQueryParam['name'] = '%' + name + '%'
    //     }
    //     if (address && address != "")
    //     {
    //         sql += " and e.address like :address"
    //         estateQueryParam['address'] = '%' + address + '%'
    //     }
    //     if (city && city != "-1")
    //     {
    //         sql += " and e.city.zoneNumber = :city "
    //         estateQueryParam['city'] = city
    //     }
    //     if (district && district != "-1")
    //     {
    //         sql += " and e.district.zoneNumber = :district "
    //         estateQueryParam['district'] = district
    //     }

    //     def countSql = " select count(e.id) from Account e where e.type.code = 'BankAccount' and e.id in " + Account.FilterAccountSql(user)
    //     countSql += sql

    //     if (order && sort)
    //     {
    //         sql += " order by e.${sort} ${order}"
    //     }
    //     else
    //     {
    //         sql += " order by e.modifiedDate desc "
    //     }
    //     estateSql += sql

    //     def accountList = Account.executeQuery(estateSql, estateQueryParam, [max: max, offset: offset])
    //     def accountCount = Account.executeQuery(countSql, estateQueryParam)
    //     respond accountList, model: [accountCount: accountCount[0], params: params], view: 'bankAccountIndex'
    // }

    // def evaluateAccountIndex()
    // {
    //     def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
    //     def offset = params.offset ? params.offset.toInteger() : 0
    //     //城市
    //     def city = params["city"]
    //     //行政区
    //     def district = params["district"]
    //     def name = params["name"]
    //     def address = params["address"]
    //     def estateQueryParam = new HashMap()
    //     def sort = params["sort"]
    //     def order = params["order"]

    //     def user = User.findById(springSecurityService.principal.id)
    //     def estateSql = " from Account e where e.type.code = 'EvaluateAccount' and e.bankAccount in " + Account.FilterAccountSql(user)
    //     def sql = " "
    //     if (name && name != "")
    //     {
    //         sql += " and e.name like :name"
    //         estateQueryParam['name'] = '%' + name + '%'
    //     }
    //     if (address && address != "")
    //     {
    //         sql += " and e.address like :address"
    //         estateQueryParam['address'] = '%' + address + '%'
    //     }
    //     if (city && city != "-1")
    //     {
    //         sql += " and e.city.zoneNumber = :city "
    //         estateQueryParam['city'] = city
    //     }
    //     if (district && district != "-1")
    //     {
    //         sql += " and e.district.zoneNumber = :district "
    //         estateQueryParam['district'] = district
    //     }

    //     def countSql = " select count(e.id) from Account e where e.type.code = 'evaluateAccountIndex' and e.bankAccount in " + Account.FilterAccountSql(user)
    //     countSql += sql

    //     if (order && sort)
    //     {
    //         sql += " order by e.${sort} ${order}"
    //     }
    //     else
    //     {
    //         sql += " order by e.modifiedDate desc "
    //     }
    //     estateSql += sql
    //     def accountList = Account.executeQuery(estateSql, estateQueryParam, [max: max, offset: offset])
    //     def accountCount = Account.executeQuery(countSql, estateQueryParam)
    //     respond accountList, model: [accountCount: accountCount[0], params: params], view: 'evaluateAccountIndex'
    // }

    /** ------------------------------其他机构 -----------------------------------**/
    def externalAccountIndex()
    {
        def code = params['code']
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        def name = params["name"]
        def contact = params["contact"]
        def phone = params["phone"]
        def city = params['city']
        def district = params['district']
        def estateQueryParam = new HashMap()
        def sort = params["sort"]
        def order = params["order"]

        def user = User.findById(springSecurityService.principal.id)
        def estateSql = " from Account e where e.type.code = '${code}' and e.bankAccount in " + Account.FilterAccountSql(user)
        def sql = " "
        if (name && name != "")
        {
            sql += " and e.name like :name"
            estateQueryParam['name'] = '%' + name + '%'
        }
        if (contact && contact != "")
        {
            sql += " and e.contact like :contact"
            estateQueryParam['contact'] = '%' + contact + '%'
        }
        if (phone && phone != "")
        {
            sql += " and e.phone like :phone"
            estateQueryParam['phone'] = phone
        }
        if (city && city != "-1")
        {
            sql += " and e.city.zoneNumber = :city"
            estateQueryParam['city'] = city
        }
        if (district && district != "-1")
        {
            sql += " and e.district.zoneNumber = :district"
            estateQueryParam['district'] = district
        }

        def countSql = " select count(e.id) from Account e where e.type.code = '${code}' and e.bankAccount in " + Account.FilterAccountSql(user)
        countSql += sql

        if (order && sort)
        {
            sql += " order by e.${sort} ${order}"
        }
        else
        {
            sql += " order by e.modifiedDate desc "
        }
        estateSql += sql
        def accountList = Account.executeQuery(estateSql, estateQueryParam, [max: max, offset: offset])
        def accountCount = Account.executeQuery(countSql, estateQueryParam)

        def districtList = District.findAllByParentAreaAndAreaLevel(City.findByZoneNumberAndAreaLevel(city, 2), 3)

        respond accountList, model: [accountCount: accountCount[0], code: code, districtList: districtList], view: 'externalAccountIndex'
    }

    def externalAccountCreate()
    {
        respond new Account(params), params["code", params['code']]
    }

    @Transactional
    def externalAccountSave(Account account)
    {
        def city = params['cityt']
        def district = params['districtt']
        def type = params['code']
        if (city && city != "-1")
        {
            account.city = City.findByZoneNumber(city)
        }
        if (district && district != "-1")
        {
            account.district = District.findByZoneNumber(district)
        }
        if (type)
        {
            account.type = AccountTypeDict.findByCode(type)
        }

        if (account == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (account.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            print account.errors
            respond account.errors, view: 'externalAccountCreate'
            return
        }

        account.save flush: true

        redirect(action: 'externalAccountIndex', params: [code: params['code']])
    }

    def externalAccountEdit(Account account)
    {
        respond account, params["code", params['code']]
    }

    @Transactional
    def externalAccountUpdate(Account account)
    {
        def city = params['cityt']
        def district = params['districtt']
        if (city && city != "-1")
        {
            account.city = City.findByZoneNumber(city)
        }
        if (district && district != "-1")
        {
            account.district = District.findByZoneNumber(district)
        }

        if (account == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (account.hasErrors())
        {
            println account.errors
            transactionStatus.setRollbackOnly()
            respond account.errors, view: 'externalAccountEdit'
            return
        }

        account.save flush: true

        redirect(action: 'externalAccountShow', params: [code: params['code']], id: account.id)
    }

    def externalAccountShow(Account account)
    {
        def user = User.findById(springSecurityService.principal.id)
        def flowStage = AccountFlowStage.findByAccountAndStage(account, account?.stage)
        def roleSql = ""
        def roleList = UserRole.findAllByUser(user)*.role
        if (roleList)
        {
            String roleIdList = roleList*.id?.toString()
            roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        }

        def editRoleFlag = false
        def approveRoleFlag = false
        if (flowStage)
        {
            editRoleFlag = AccountFlowStageRole.find("from AccountFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.EDIT()?.id]) && true
            approveRoleFlag = AccountFlowStageRole.find("from AccountFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.APPROVAL()?.id]) && true
        }

        def layout = AccountFlowStage.findByAccountAndStage(account, account?.stage)?.layout?.name

        respond account, model: [editRoleFlag: editRoleFlag, approveRoleFlag: approveRoleFlag, params: params], view: layout
    }

    @Transactional
    def delete(Account account)
    {

        if (account == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        account.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'account.label', default: 'account'), account.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    // *********************************银行机构*********************************

    def accountIndex(Integer max)
    {

        def accountImport = false
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        // 总行机构，无下属机构，显示添加机构功能
        if (user?.account?.level?.code == "0" && !Account.findAllByParent(user?.account))
        {
            accountImport = true
        }

        params.max = Math.min(max ?: 10, 100)
        respond new Account(), model: [accountCount: Account.count(), accountImport: accountImport]
    }

    @Transactional
    def accountSave(Account account)
    {
        if (account == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (account.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond account.errors, view: 'accountIndex'
            return
        }

        account.type = AccountTypeDict.BANK()
        if (account.validate())
        {
            account.save flush: true
        }
        else
        {
            println account.errors
        }

        // 新增
        if (!params["id"])
        {
            // 递归查出所有上级机构（包括自己）
            def accountList = accountService.getAllParent(account, [])
            accountList?.each {
                def accountManageAccount = new AccountManageAccount()
                accountManageAccount.account = it
                accountManageAccount.manageAccount = account
                accountManageAccount.save()
            }
        }

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'account.label', default: 'Account'), account.id])
                redirect action: 'accountIndex'
            }
            '*' { respond account, [status: CREATED] }
        }
    }

    def getAllAccountList()
    {
        def sql = "select new map(o.id as id, o.parent.id as pId, o.name as name) from Account o where o.type.code = 'BankAccount'"
        def name = params['name']
        if (name)
        {
            sql += " and o.name like '%${name}%'"
        }
        sql += " order by level, name"

        def accountList = Account.executeQuery(sql).asList()
        render([status: "success", accountList: accountList] as JSON)
    }

    @Transactional
    def editAccount()
    {
        def id = params["id"]
        def name = params["name"]
        if (!id || !name)
        {
            render([message: "参数信息不全，请重试", status: "Failed"] as JSON)
            return
        }

        def account = Account.findById(id)
        account.name = name
        if (account.validate())
        {
            account.save flush: true
        }
        else
        {
            println account.errors
        }

        render([status: "success"] as JSON)
    }

    @Transactional
    def addAccount()
    {
        def pId = params["pId"]

        def account = new Account()
        account.name = "new node"
        account.parent = Account.findById(pId)
        if (account.validate())
        {
            account.save flush: true
        }
        else
        {
            println account.errors
        }

        // 递归查出所有上级机构（包括自己）
        def accountList = accountService.getAllParent(account, [])
        accountList?.each {
            def accountManageAccount = new AccountManageAccount()
            accountManageAccount.account = it
            accountManageAccount.manageAccount = account
            accountManageAccount.save()
        }

        render([status: "success", account: account] as JSON)
    }

    @Transactional
    def deleteAccount()
    {
        def id = params["id"]
        def account = Account.findById(id)

        def accountManageAccountList = AccountManageAccount.findAll("from AccountManageAccount as o where o.account.id = ${id} or o.manageAccount.id = ${id}")
        accountManageAccountList?.each {
            it?.delete flush: true
        }

        account.delete flush: true

        render([status: "success"] as JSON)
    }

    def queryAccountById()
    {
        def id = params["id"]
        def account = Account.findById(id)
        render([status: "success", account: account] as JSON)
    }

    def queryAllAccountManageById()
    {
        def id = params["id"]
        def resultList = AccountManageAccount.findAllByAccount(Account.findById(id))

        def accountManageList = []
        def sql = "select new map(o.id as id, o.parent.id as pId, o.name as name) from Account o where o.type.code = 'BankAccount' order by level, name"
        def accountList = Account.executeQuery(sql).asList()
        accountList?.each {
            if (it?.id in resultList*.manageAccount.id)
            {
                def item = [id: it?.id, pId: it?.pId, name: it?.name, checked: true, open: true]
                accountManageList.add(item)
            }
            else
            {
                def item = [id: it?.id, pId: it?.pId, name: it?.name, checked: false, open: true]
                accountManageList.add(item)
            }
        }
        render([status: "success", accountManageList: accountManageList] as JSON)
    }

    @Transactional
    def addAccountManageAccount()
    {
        def id = params["id"]
        def manageId = params["manageId"]
        def flag = params["flag"]

        def account = Account.findById(id)
        def manageAccount = Account.findById(manageId)

        if (flag == "true")
        {
            // 添加权限
            def accountManageAccount = new AccountManageAccount()
            accountManageAccount.account = account
            accountManageAccount.manageAccount = manageAccount
            accountManageAccount.save flush: true

            render([status: "success"] as JSON);
        }
        else
        {
            // 删除权限
            def accountManageAccount = AccountManageAccount.findByAccountAndManageAccount(account, manageAccount)
            accountManageAccount?.delete flush: true

            render([status: "success"] as JSON)
        }
    }

    def accountDataMigration(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        params.sort = "modifiedDate"
        params.order = "desc"
        respond Account.list(params), model: [accountCount: Account.count()]
    }

    // 数据迁移页面搜索
    def searchAccountData()
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0;

        def name = params["name"]
        def contact = params["contact"]
        def phone = params["phone"]
        def cellphone = params["cellphone"]

        String sql = "from Account as o where 1=1"
        if (name)
        {
            sql += " and o.name like '%${name}%'"
        }
        if (contact)
        {
            sql += " and o.contact like '%${contact}%'"
        }
        if (phone)
        {
            sql += " and o.phone like '%${phone}%'"
        }
        if (cellphone)
        {
            sql += " and o.cellphone like '%${cellphone}%'"
        }
        sql += ' order by modifiedDate desc'

        println "sql:" + sql

        def max = params.max
        def offset = params.offset

        def list = Account.findAll(sql, [max: max, offset: offset])
        def list1 = Account.findAll(sql)
        def count = list1.size()

        respond list, model: [accountCount: count, params: params], view: 'accountDataMigration'
    }

    @Transactional
    def dataMigration()
    {
        def oldAccountId = params["oldAccountId"]
        def newAccountId = params["newAccountId"]

        def oldAccount = Account.findById(oldAccountId)
        if (!oldAccountId || !oldAccount)
        {
            flash.message = "迁移失败，请重试！"
            redirect action: 'accountDataMigration'
        }
        def newAccount = Account.findById(newAccountId)
        if (!newAccountId || !newAccount)
        {
            flash.message = "迁移失败，请重试！"
            redirect action: 'accountDataMigration'
        }

        def estateList = Estate.findAllByAccount(oldAccount)
        estateList?.each {
            it?.account = newAccount
            it?.save()
        }

        redirect action: 'accountDataMigration'
    }

    @Transactional
    def accountCsvImport()
    {
        // 读取文件
        def file = request.getFile('myFile')
        def fileCharset = FileUtil.GetFileCharset(file.getInputStream())
        def status = "success"

        //将文件传给对应类,读取文件
        try
        {
            def importer = new AccountCSVImporter()
            def estateMapList = importer.read(file.getInputStream(), fileCharset)
            accountService.accountInserts(estateMapList)
        }
        catch (Exception e)
        {
            status = "failed"
            println e.printStackTrace()
        }

        redirect action: 'index', params: [status: status]
    }

    /*
    * 获取zoneNumber
    * */

    def getZoneNumber()
    {
        def db = new groovy.sql.Sql(dataSource)
        def id = params['id'];
        def sql = "SELECT * FROM area A WHERE area_id = " + id
        def result = db.rows(sql).asList()
        db.close()
        render([result: result] as JSON)
    }

    def getAccountList()
    {
        def city = params['city']
        def name = params['name']
        def result = Account.executeQuery("select new map(o.id as id, o.name as name, o.address as address, o.x as x, o.y as y) from Account o where o.city.zoneNumber = '${city}' and o.name like '%${name}%'").asList()
        render([result: result] as JSON)
    }

    // def evaluateAccountCreate()
    // {
    //     respond new Account(params)
    // }

    // @Transactional
    // def evaluateAccountSave(Account account)
    // {
    //     if (account == null)
    //     {
    //         transactionStatus.setRollbackOnly()
    //         notFound()
    //         return
    //     }

    //     if (account.hasErrors())
    //     {
    //         transactionStatus.setRollbackOnly()
    //         respond account.errors, view: 'evaluateAccountCreate'
    //         return
    //     }

    //     account.save flush: true

    //     redirect action: 'evaluateAccountIndex'
    // }

    // def evaluateAccountEdit(Account account)
    // {
    //     respond account
    // }

    // @Transactional
    // def evaluateAccountUpdate(Account account)
    // {
    //     if (account == null)
    //     {
    //         transactionStatus.setRollbackOnly()
    //         notFound()
    //         return
    //     }

    //     if (account.hasErrors())
    //     {
    //         transactionStatus.setRollbackOnly()
    //         respond account.errors, view: 'evaluateAccountEdit'
    //         return
    //     }

    //     account.save flush: true

    //     redirect(action: 'evaluateAccountShow', params: [id:account.id])
    // }

    // def evaluateAccountShow(Account account)
    // {
    //     respond account
    // }

    def initAccountflow(Account account)
    {
        def workflow = account.workflow
        accountService.initAccountFlowStage(account, workflow)

        redirect action: 'externalAccountShow', id: account?.id, params: [code: params.code]
    }

    // 登记流程推进
    def approve(Account account)
    {
        def user = User.findById(springSecurityService.principal.id)
        def flowStage = AccountFlowStage.findByAccountAndStage(account, account?.stage)
        def roleSql = ""
        def roleList = UserRole.findAllByUser(user)*.role
        if (roleList)
        {
            String roleIdList = roleList*.id?.toString()
            roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        }

        def approveRoleFlag = AccountFlowStageRole.find("from AccountFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.APPROVAL()?.id]) && true
        if (!approveRoleFlag)
        {
            flash.message = "权限校验失败"
            redirect action: 'externalAccountShow', id: account?.id, params: [code: params.code]
            return
        }

        // 校验是否提交备注
        def comment = Comment.findByAccountAndAccountStage(account, account?.stage)
        if (!comment)
        {
            flash.message = "未提交审批意见"
            redirect action: 'externalAccountShow', id: account?.id, params: [code: params.code]
            return
        }

        def map = accountService.approve(account)
        if (!map['flag'])
        {
            flash.message = map['message']
            redirect action: 'externalAccountShow', id: account?.id, params: [code: params.code]
            return
        }

        redirect action: 'externalAccountIndex', params: [code: params.code]
    }

    def reject(Account account)
    {
        def user = User.findById(springSecurityService.principal.id)
        def flowStage = AccountFlowStage.findByAccountAndStage(account, account?.stage)
        def roleSql = ""
        def roleList = UserRole.findAllByUser(user)*.role
        if (roleList)
        {
            String roleIdList = roleList*.id?.toString()
            roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        }

        def approveRoleFlag = AccountFlowStageRole.find("from AccountFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.APPROVAL()?.id]) && true
        if (!approveRoleFlag)
        {
            flash.message = "权限校验失败"
            redirect action: 'externalAccountShow', id: account?.id, params: [code: params.code]
            return
        }

        def canReject = accountService.reject(account)
        if (canReject)
        {
            def comment = new Comment()
            comment.account = account
            comment.accountStage = account?.stage
            comment.comment = params['comment']
            comment.save flush: true

            redirect action: 'externalAccountIndex', params: [code: params.code]
        }
        else
        {
            flash.message = "对不起，无权限拒绝"
            redirect action: 'externalAccountShow', id: account?.id, params: [code: params.code]
            return
        }
    }

}
